﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.Organizations.Repository;
using Mozhi.Abp.Core.Networks;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;

namespace mozhi.smarterp.BasicData.Organizations.Service
{
    public class OrganizationManager : DomainService
    {
        private IOrganizationRepository _repository;

        private IRemoteServiceClient _remoteServiceClient;

        public OrganizationManager(IOrganizationRepository repository, IRemoteServiceClient remoteServiceClient)
        {
            _repository = repository;
            _remoteServiceClient = remoteServiceClient;
        }

        public async Task<Organization> ChangeAsync(Guid id, string officialName, string taxIdNumber, Guid? standardCurrencyId, AccountingStandardType accountingStandard, DateTime? activatedDate)
        {
            var organization = await _repository.FirstOrDefaultAsync();

            if (organization == null)
                throw new UserFriendlyException($"组织：{id}不存在", "100000");

            var journalCount = await _remoteServiceClient.GetAsync<int>("Finance", "api/v1/journals/count?period=");
            var balanceCount = await _remoteServiceClient.GetAsync<int>("Finance", "api/v1/journals/count?period=");
            //变更了会计准则
            if (organization.AccountingStandard != default && organization.AccountingStandard != accountingStandard)
            {
                //校验有没有科目余额，凭证，结账记录
                if (journalCount > 0)
                    throw new UserFriendlyException("存在凭证，不允许更改会计准则", "100000");

                if (journalCount > 0)
                    throw new UserFriendlyException("存在科目余额，不允许更改会计准则", "100000");

            }

            if (organization.StandardCurrencyId.HasValue && organization.StandardCurrencyId != standardCurrencyId)
            {
                //校验有没有科目余额，凭证，结账记录
                if (journalCount > 0)
                    throw new UserFriendlyException("存在凭证，不允许更改本位币", "100000");

                if (journalCount > 0)
                    throw new UserFriendlyException("存在科目余额，不允许更改本外币", "100000");
            }

            if (organization.ActivatedDate.HasValue && organization.ActivatedDate != activatedDate)
            {
                //校验有没有科目余额，凭证，结账记录
                if (journalCount > 0)
                    throw new UserFriendlyException("存在凭证，不允许更改启用", "100000");

                if (journalCount > 0)
                    throw new UserFriendlyException("存在科目余额，不允许更改启用日期", "100000");
            }

            organization.Change(officialName, taxIdNumber, standardCurrencyId, accountingStandard, activatedDate);

            return organization;
        }
    }
}
